package com.itstyle.quartz.interceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.itstyle.quartz.common.IPUtils;
import com.itstyle.quartz.common.UrlParams;


@Component
public class ParamInterceptor implements HandlerInterceptor
{

    private final static Logger logger = LoggerFactory.getLogger(ParamInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler)
        throws Exception
    {
        String url = request.getRequestURL().toString();
        String uri = request.getRequestURI();
        String queryStr = UrlParams.getUrlFromMap(request);
        String ip = IPUtils.getClientAddress(request);
        if (StringUtils.isNotBlank(uri) && !uri.contains("."))
        {
            // 请求路径和参数的打印
            if (StringUtils.isNotBlank(queryStr))
            {
                // logger.info(
                // "url: " + request.getRequestURL() + "?" + queryStr + " " + "ip:" + ip);
            }
            else
            {
                // logger.info("url: " + request.getRequestURL() + " " + "ip:" + ip);
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView)
        throws Exception
    {
        // 啥也不干
        // logger.info(request.getRequestURL().toString());

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex)
        throws Exception
    {
        response.addHeader("Access-Control-Allow-Origin", "*");
        // logger.info(request.getRequestURL().toString());

    }

}
